//
//  CYABDetailVC.m
//  CreditAddressBook
//
//  Created by Lee on 15/9/30.
//  Copyright © 2015年 Lee. All rights reserved.
//

#import "CYABDetailVC.h"
#import "DSNavigationBar.h"
#import "CYABPhoneVC.h"
#import "GCD.h"
#import "LEBarButtonItem.h"
#import "CYCallRecords.h"
#import "CYDialTool.h"
#import "CYCallRecord.h"
#import "CYStatisticsContentVC.h"
#import "CYStatisticsTopView.h"
#import "CYCallRecordsTableVC.h"
#import "CYDatabase.h"

static const CGFloat _bottomViewConstraint = 60;//sb中底部约束超出superview的距离

@interface CYABDetailVC ()<UIScrollViewDelegate>

@property (weak, nonatomic) IBOutlet UIView *segmentViewLine;

@property (weak, nonatomic) IBOutlet UIView *bottomLine4;
@property (weak, nonatomic) IBOutlet UIView *bottomLine3;
@property (weak, nonatomic) IBOutlet UIView *bottomLine04;
@property (weak, nonatomic) IBOutlet UIView *bottomLine03;
@property (weak, nonatomic) IBOutlet UIScrollView *abScrollView;
@property (weak, nonatomic) IBOutlet UIView *abscrollViewContentIVew;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *contentIViewH;//UIScrollView滚动内容的高度
@property (weak, nonatomic) IBOutlet UIView *bottomContentIView;//下部内容view
@property (weak, nonatomic) IBOutlet UIView *segmentIView;//移动的导航条
@property (weak, nonatomic) IBOutlet UIView *segmentView0;//固定的导航条
@property (weak, nonatomic) IBOutlet UIView *topIView;//头部view
@property (weak, nonatomic) IBOutlet UIImageView *headImageView;//头像
@property (weak, nonatomic) IBOutlet UILabel *nameLabel;//姓名
@property (weak, nonatomic) IBOutlet UILabel *noteLabel;//备注
@property (weak, nonatomic) IBOutlet UIButton *collectionBtn;//收藏按钮

@property (nonatomic , assign) CGFloat segmentBottomLineX;//segmentBottomLine的X值，适配ios7
@property (nonatomic , assign) NSInteger fromIndex;//导航条下标缓存

@property (nonatomic , strong) CYABPhoneVC *phoneVC;//电话详情
@property (nonatomic , strong) CYCallRecordsTableVC *callRecordsVC;//通话记录
@property (nonatomic ,strong) CYStatisticsContentVC *statisVC;//统计
@property (nonatomic ,strong) UIViewController *currentVC;//当前显示的控制器

@property (nonatomic ,strong) NSArray *lines;
@end

@implementation CYABDetailVC

- (NSArray *)lines {
    if (!_lines) {
        _lines = @[self.bottomLine03, self.bottomLine04, self.bottomLine4, self.bottomLine3];
    }
    return _lines;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupOther];
    [self setupSubController];
    [self setupPerson];
}

- (void)setupOther {
    //不自动滚动
    self.automaticallyAdjustsScrollViewInsets = NO;
    //    self.abScrollView.bounces = NO;//弹簧效果
    
    //设置头像边框
    self.headImageView.layer.cornerRadius = self.headImageView.width/2;
    self.headImageView.layer.masksToBounds = YES;
    self.headImageView.layer.borderColor = CYNaviThemeColor1.CGColor;
    self.headImageView.layer.borderWidth = 5;
    
    //添加更多按钮
    LEBarButtonItem *itema = [[LEBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"icon_overflowmenu"] andSelImage:nil andTitle:@"更多" target:self action:@selector(moreBtn)];
    self.navigationItem.rightBarButtonItem = itema;
}

- (void)setupSubController {
    //电话详情控制器
    CYABPhoneVC *phoneVC = [[CYABPhoneVC alloc] init];
    phoneVC.person = self.person;
    self.phoneVC = phoneVC;
    self.currentVC = phoneVC;
    [self addChildViewController:phoneVC];
    phoneVC.view.y = 10;
    //计算滚动的高度
    [self contentSizeH:phoneVC.phoneVCHeight];
    
    [self.bottomContentIView layoutIfNeeded];
    self.bottomContentIView.height = phoneVC.phoneVCHeight;
    [self.bottomContentIView addSubview:phoneVC.view];
    [phoneVC didMoveToParentViewController:self];
    
    //通话记录
    CYCallRecords *calls = [CYCallRecords loadFromNibUsingClassName];
    calls.callRecords = [self loadCallHistory:self.person.phones];
    calls.scrollEnabled = NO;
    UIViewController *callRecordsVC = [[UIViewController alloc] init];
    callRecordsVC.view = calls;
    callRecordsVC.view.height = calls.viewH;
//    self.callRecordsVC = callRecordsVC;
    
    CYCallRecordsTableVC *callRecords = [[CYCallRecordsTableVC alloc] init];
    callRecords.callRecords = [self loadCallHistory:self.person.phones];
    self.callRecordsVC = callRecords;
    
    //统计
    CYStatisticsContentVC *statiVC = [[CYStatisticsContentVC alloc] init];
    statiVC.person = self.person;
    self.statisVC = statiVC;
    CYStatisticsTopView *topview = [CYStatisticsTopView topView];
    statiVC.topView = topview;
    statiVC.view.frame = self.bottomContentIView.bounds;
    
    //失信人详情
    
}

- (void)moreBtn {
    
}

- (void)setupPerson {
    if (self.person.person) {
        self.nameLabel.text = self.person.name;
        if (self.person.person.note) {
            self.noteLabel.text = self.person.person.note;
        } else {
            self.noteLabel.text = @"空";
        }
        if (self.person.person.thumbnail) {
            self.headImageView.image = self.person.person.thumbnail;
        }
    }
}

- (IBAction)segmentBtnClick:(UIButton *)sender {
    if (sender.tag == self.fromIndex) return;
    [self segmentBottomLines:self.lines to:sender.tag];
    [self.abScrollView setContentOffset:CGPointZero animated:YES];
    switch (sender.tag) {
        case CYIndexFirst:
//            [self contentSizeH:0];
            [self replaceController:self.currentVC newController:self.statisVC];
            break;
            
        case CYIndexSecond:
            [self contentSizeH:self.callRecordsVC.viewH];
            [self replaceController:self.currentVC newController:self.callRecordsVC];
            break;
            
        case CYIndexThird:
            [self contentSizeH:self.phoneVC.phoneVCHeight];
            [self replaceController:self.currentVC newController:self.phoneVC];
            break;
            
        case CYIndexFourth:
            [self replaceController:self.currentVC newController:self.phoneVC];
            break;
    }
}

- (IBAction)changeHeadBtn:(id)sender {
    
}

/**
 *  收藏
 *
 *  @param sender <#sender description#>
 */
- (IBAction)collectionBtn:(UIButton *)sender {
    sender.selected = YES;
}

/**
 *  导航条动画效果
 *
 *  @param lines
 *  @param to
 */
- (void)segmentBottomLines:(NSArray *)lines to:(NSInteger)to {
    CYLog(@"to:%ld", (long)to);
    UIView *line = lines.firstObject;
    if (!self.segmentBottomLineX) {
        self.segmentBottomLineX = line.x;
    }
    NSInteger index = to - self.fromIndex;
    //16为SB中减去的宽度
    self.segmentBottomLineX += index * (line.width + 16);
    //动画效果
    [UIView animateWithDuration:.5f delay:0 usingSpringWithDamping:.5 initialSpringVelocity:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
        for (UIView *line in lines) {
            line.x = self.segmentBottomLineX;
        }
    } completion:nil];
    self.fromIndex = to;
}

- (void)contentSizeH:(CGFloat)height {
    //计算滚动的高度
    CGFloat viewH = height + self.topIView.height + _bottomViewConstraint;
    if (viewH < CYScreeSize.height) {
        viewH = CYScreeSize.height;
    }
    self.contentIViewH.constant = viewH;
}

#pragma mark - scrollView代理
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    //设置导航条的固定与移动
    if (scrollView.contentOffset.y >= self.topIView.height - 64 - 41) {
        self.segmentView0.hidden = NO;
        self.segmentIView.hidden = YES;
    } else {
        self.segmentView0.hidden = YES;
        self.segmentIView.hidden = NO;
    }
    
    //设置导航栏颜色变化
    CGFloat alpha = scrollView.contentOffset.y/self.topIView.height;
    if (alpha < .5) {
        alpha = .0;
    } else if (alpha > 1) {
        alpha = 1.f;
    }
    [DSNavigationBar setNavigationBarWithNavigationBar:self.navigationController.navigationBar color:CYNaviThemeColorWithAlpha(alpha)];
}

#pragma mark - 多控制器切换
/**
 *	切换各个标签内容
 *  transitionFromViewController:toViewController:duration:options:animations:completion:
 *  fromViewController	  当前显示在父视图控制器中的子视图控制器
 *  toViewController		将要显示的姿势图控制器
 *  duration				动画时间(这个属性,old friend 了 O(∩_∩)O)
 *  options				 动画效果(渐变,从下往上等等,具体查看API)
 *  animations			  转换过程中得动画
 *  completion			  转换完成
 */
- (void)replaceController:(UIViewController *)oldController newController:(UIViewController *)newController {
    [self addChildViewController:newController];
    [self transitionFromViewController:oldController toViewController:newController duration:0 options:UIViewAnimationOptionTransitionNone animations:nil completion:^(BOOL finished) {
        if (finished) {
            [newController didMoveToParentViewController:self];
            [oldController willMoveToParentViewController:nil];
            [oldController removeFromParentViewController];
            self.currentVC = newController;
        }else{
            self.currentVC = oldController;
        }
    }];
}

#pragma mark - 方法重写
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [DSNavigationBar setNavigationBarWithNavigationBar:self.navigationController.navigationBar color:[UIColor clearColor]];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
//    [DSNavigationBar setNavigationBarWithNavigationBar:self.navigationController.navigationBar color:[UIColor clearColor]];
    //默认选中第三个按钮
    [self segmentBottomLines:self.lines to:CYIndexThird];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [DSNavigationBar setNavigationBarWithNavigationBar:self.navigationController.navigationBar color:CYNaviThemeColor];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [DSNavigationBar setNavigationBarWithNavigationBar:self.navigationController.navigationBar color:CYNaviThemeColor];
}

#pragma mark - 数据库操作
/**
 *  加载通话记录
 */
- (NSArray *)loadCallHistory:(NSArray *)phones {
    NSMutableArray *calls = [NSMutableArray array];
    for (NSString *phone in phones) {
        NSArray *arr = [[CYDatabase sharedDatabase] callHistorysWithParam:@{@"phone": phone}];
        if (arr && arr.count) {
            [calls addObjectsFromArray:arr];
        }
    }
    return calls;
}
@end
